﻿namespace Exporter.Exporters.Implementations
{
    using System;
    using System.IO;
    using iTextSharp.text;
    using iTextSharp.text.pdf;

    /// <summary>
    /// The Pdf exorter.
    /// </summary>
    public class PdfExporter : IFileExporter
    {
        #region IFileExplorter Membres

        /// <summary>
        /// Exports the specified fil name.
        /// </summary>
        /// <param name="filName">Name of the fil.</param>
        /// <param name="movies">The movies.</param>
        public void Export(string filName, System.Collections.Generic.IEnumerable<MoviesDataBase.Movie> movies)
        {
            Document doc = new Document();
            try
            {
                PdfWriter.GetInstance(doc, new FileStream(filName, FileMode.OpenOrCreate));
                doc.Open();

                Font titleFont = new Font() { Size = 20 };

                foreach (var movie in movies)
                {
                    PdfPTable table = new PdfPTable(2) { WidthPercentage = 100 };

                    try
                    {
                        Image image = Image.GetInstance(new Uri(movie.Poster, UriKind.Absolute));
                        PdfPCell cell = new PdfPCell(image, true) { Width = 200, BorderWidth = 0, BackgroundColor = BaseColor.WHITE };
                        table.AddCell(cell);
                    }
                    catch (UriFormatException)
                    {
                        table.AddCell(new Phrase());
                    }

                    Paragraph paragraph = new Paragraph();
                    paragraph.Add(new Paragraph(movie.Title, titleFont));
                    paragraph.Add(new Paragraph(string.Format("Genre : {0}", movie.Genre)));
                    paragraph.Add(new Paragraph(string.Format("Date de sortie : {0}", movie.DateSortie)));
                    paragraph.Add(new Paragraph(string.Format("Nationalité : {0}", movie.Nationalite)));
                    paragraph.Add(new Paragraph(string.Format("Synopsis : {0}", movie.Synopsis)));

                    table.AddCell(paragraph);
                    doc.Add(table);
                    doc.NewPage();
                }
            }
            catch (DocumentException de)
            {
                Console.Write(de.Message);
            }
            catch (IOException ie)
            {
                Console.Write(ie.Message);
            }
            catch (Exception e)
            {
                Console.Write(e.Message);
            }
            finally
            {
                doc.Close();
            }
        }

        #endregion
    }
}
